<template>
  <div class="search-suggestion">
    <van-cell
      icon="search" @click="$emit('search', item)"
      v-for="(item, index) in suggestions" :key="index"
    >
    <template #title>
      <div v-html="highlight(item)"></div>
    </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestionsAPI } from '../../../api/index.js'
// lodash 支持按需加载，有利于打包结果优化
import { debounce } from 'lodash'

export default {
  name: 'SearchSuggestion',
  data () {
    return {
      suggestions: [] // 联想建议数据列表
    }
  },
  props: {
    searchText: {
      type: String,
      default: ''
    }
  },
  watch: {
    searchText: {
      immediate: true,
      handler: debounce(function (value) {
        this.loadSearchSuggestion(value)
      }, 400)
      // handler (newVal) {
      //   this.loadSearchSuggestion(newVal)
      // }
    }
  },
  methods: {
    async loadSearchSuggestion (q) {
      try {
        const res = await getSearchSuggestionsAPI(q)
        // 有的时候后端会返回一个[null],或者[],可以主动的将这两种情况改为searchInput的值做为第一个元素
        if (res.data.data.options.length === 0 || res.data.data.options[0] === null) {
          // 如果数组中没有值,或者只有一个元素为null 时
          res.data.data.options[0] = this.searchText
        }
        this.suggestions = res.data.data.options
      } catch (error) {
        this.$toast('数据获取失败,稍后重试')
      }
    },

    highlight (val) {
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return val.replace(reg, highlightStr)
      // const tempStr = val.split(this.searchText).join(highlightStr)
      // return tempStr
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
  :deep(.active) {
    color: #3296fa;
  }
}
</style>
